package zl.ordermanager.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zl.ordermanager.dao.CustomerCallDao;
import zl.ordermanager.dao.CustomerDao;
import zl.ordermanager.po.Tcustomer;
import zl.ordermanager.po.Tcustomercall;
import zl.ordermanager.service.CustomerCallService;
import zl.ordermanager.utils.ConfigUtil;
import zl.ordermanager.vo.CustomerCall;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.PageHelper;
import zl.ordermanager.vo.SessionInfo;
import zl.ordermanager.vo.Total;

@Service
public class CustomerCallServiceImpl implements CustomerCallService {

	@Autowired
	private CustomerCallDao customerCallDao;

	@Autowired
	private CustomerDao customerDao;

	@Override
	public DataGrid<CustomerCall> dataGrid(HttpSession session, PageHelper pageHelper, Total total) {
		DataGrid<CustomerCall> dataGrid = new DataGrid<CustomerCall>();
		List<CustomerCall> customerCallList = new ArrayList<CustomerCall>();
		Map<String, Object> params = new HashMap<String, Object>();
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			params.put("keyword", "%%" + pageHelper.getKeywords() + "%%");
		}
		if (pageHelper.getStartContactDate() != null && !pageHelper.getStartContactDate().isEmpty()
				&& pageHelper.getStopContactDate() != null && !pageHelper.getStopContactDate().isEmpty()) {
			params.put("startContactDate", pageHelper.getStartContactDate());
			params.put("stopContactDate", pageHelper.getStopContactDate());
		}
		if (pageHelper.getCustomer() != null && !pageHelper.getCustomer().isEmpty()) {
			params.put("customer", "%%" + pageHelper.getCustomer() + "%%");
		}
		if (pageHelper.getSalesman() != null && !pageHelper.getSalesman().isEmpty()) {
			params.put("salesman", pageHelper.getSalesman());
		}
		if (pageHelper.getContactResult() != null && !pageHelper.getContactResult().isEmpty()) {
			params.put("result", pageHelper.getContactResult());
		}
		String hql = " from Tcustomercall t ";
		String whereHql = whereHql(session, pageHelper);
		List<Tcustomercall> tcustomercallList = customerCallDao.find(hql + whereHql + orderHql(pageHelper), params,
				pageHelper.getPageNum(), pageHelper.getNumPerPage());
		if (tcustomercallList != null && tcustomercallList.size() > 0) {
			for (Tcustomercall tcustomercall : tcustomercallList) {
				CustomerCall customerCall = new CustomerCall();
				BeanUtils.copyProperties(tcustomercall, customerCall);
				customerCallList.add(customerCall);
			}
		}
		dataGrid.setList(customerCallList);
		dataGrid.setTotal(customerCallDao.count("select count(*) " + hql + whereHql, params));
		total.setCount(String.valueOf(customerCallDao.count("select count(*) " + hql + whereHql, params)));
		return dataGrid;
	}

	private String whereHql(HttpSession session, PageHelper pageHelper) {
		String whereString = "";
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			whereString += "where (t.contactDate like :keyword ";
			whereString += " or t.customer like :keyword ";
			whereString += " or t.customerType like :keyword ";
			whereString += " or t.address like :keyword ";
			whereString += " or t.contacts like :keyword ";
			whereString += " or t.department like :keyword ";
			whereString += " or t.job like :keyword ";
			whereString += " or t.telephone like :keyword ";
			whereString += " or t.phone like :keyword ";
			whereString += " or t.fax like :keyword ";
			whereString += " or t.otherContact like :keyword ";
			whereString += " or t.requirment like :keyword ";
			whereString += " or t.remarks like :keyword ";
			whereString += " or t.result like :keyword ";
			whereString += " or t.salesman like :keyword)";
		}
		if (pageHelper.getStartContactDate() != null && !pageHelper.getStartContactDate().isEmpty()
				&& pageHelper.getStopContactDate() != null && !pageHelper.getStopContactDate().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (str_to_date(t.contactDate, '%Y-%c-%e') >= :startContactDate and str_to_date(t.contactDate, '%Y-%c-%e') <= :stopContactDate)";
			} else {
				whereString += " and (str_to_date(t.contactDate, '%Y-%c-%e') >= :startContactDate and str_to_date(t.contactDate, '%Y-%c-%e') <= :stopContactDate)";
			}
		}
		if (pageHelper.getSalesman() != null && !pageHelper.getSalesman().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.salesman = :salesman)";
			} else {
				whereString += " and (t.salesman = :salesman)";
			}
		}
		if (pageHelper.getCustomer() != null && !pageHelper.getCustomer().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.customer like :customer)";
			} else {
				whereString += " and (t.customer like :customer)";
			}
		}
		if (pageHelper.getContactResult() != null && !pageHelper.getContactResult().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.result = :result)";
			} else {
				whereString += " and (t.result = :result)";
			}
		}

		/*
		String userFilter = "";
		SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		if (sessionInfo != null) {
			if (sessionInfo.getRole().equals("业务员")) {
				userFilter = " (t.salesman = '" + sessionInfo.getRealname() + "')";
			}
		}

		if (!userFilter.isEmpty()) {
			if (!whereString.isEmpty()) {
				whereString = whereString + " and " + userFilter;
			} else {
				whereString = "where " + userFilter;
			}
		}
		*/

		return whereString;
	}

	private String orderHql(PageHelper pageHelper) {
		String orderString = "";
		if (pageHelper.getOrderField() != null && !pageHelper.getOrderField().isEmpty()
				&& pageHelper.getOrderDirection() != null && !pageHelper.getOrderDirection().isEmpty()) {
			orderString = " order by t." + pageHelper.getOrderField() + " " + pageHelper.getOrderDirection();
		}
		return orderString;
	}

	@Override
	public CustomerCall get(Integer id) {
		Tcustomercall tcustomercall = customerCallDao.get(Tcustomercall.class, id);
		if (tcustomercall == null) {
			return null;
		}
		CustomerCall customerCall = new CustomerCall();
		BeanUtils.copyProperties(tcustomercall, customerCall);
		return customerCall;
	}

	@Override
	public void add(CustomerCall customerCall) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		String contactDate = customerCall.getContactDate();
		params.put("contactDateMonth", contactDate.substring(0, contactDate.lastIndexOf('-')));
		params.put("customer", customerCall.getCustomer());
		params.put("salesman", customerCall.getSalesman());
		if (customerCallDao
				.count("select count(*) from Tcustomercall t where t.customer = :customer and date_format(str_to_date(t.contactDate, '%Y-%c-%e'), '%Y-%c') = :contactDateMonth and t.salesman = :salesman",
						params) >= 3) {
			throw new Exception("本月同一客户已联系三次，不能再次添加！");
		}
		Tcustomercall tcustomercall = new Tcustomercall();
		BeanUtils.copyProperties(customerCall, tcustomercall);
		customerCallDao.save(tcustomercall);
		params.clear();
		params.put("customer", customerCall.getCustomer());
		params.put("contacts", customerCall.getContacts());
		if (customerDao.count(
				"select count(*) from Tcustomer t where t.customer = :customer and contacts = :contacts", params) < 1) {
			Tcustomer tcustomer = new Tcustomer();
			BeanUtils.copyProperties(customerCall, tcustomer);
			tcustomer.setId(null);
			customerDao.save(tcustomer);
		}
	}

	@Override
	public void edit(CustomerCall customerCall) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		String contactDate = customerCall.getContactDate();
		params.put("contactDateMonth", contactDate.substring(0, contactDate.lastIndexOf('-')));
		params.put("customer", customerCall.getCustomer());
		params.put("salesman", customerCall.getSalesman());
		if (customerCallDao
				.count("select count(*) from Tcustomercall t where t.customer = :customer and date_format(str_to_date(t.contactDate, '%Y-%c-%e'), '%Y-%c') = :contactDateMonth and t.salesman = :salesman",
						params) >= 3) {
			List<Tcustomercall> tcustomercallList = customerCallDao
					.find("select count(*) from Tcustomercall t where t.customer = :customer and date_format(str_to_date(t.contactDate, '%Y-%c-%e'), '%Y-%c') = :contactDateMonth and t.salesman = :salesman",
							params);
			boolean isFound = false;
			for (Tcustomercall tcustomercall : tcustomercallList) {
				if (tcustomercall.getId().intValue() == customerCall.getId().intValue()) {
					isFound = true;
				}
			}
			if (!isFound) {
				throw new Exception("本月同一客户已联系三次，修改失败！");
			}
		} 
		Tcustomercall tcustomercall = customerCallDao.get(Tcustomercall.class, customerCall.getId());
		BeanUtils.copyProperties(customerCall, tcustomercall);
		params.clear();
		params.put("customer", customerCall.getCustomer());
		params.put("contacts", customerCall.getContacts());
		if (customerDao.count(
				"select count(*) from Tcustomer t where t.customer = :customer and contacts = :contacts", params) < 1) {
			Tcustomer tcustomer = new Tcustomer();
			BeanUtils.copyProperties(customerCall, tcustomer);
			tcustomer.setId(null);
			customerDao.save(tcustomer);
		}
	}

	@Override
	public void delete(Integer id) {
		customerCallDao.delete(customerCallDao.get(Tcustomercall.class, id));
	}

}
